#include "rpn.h"

int find_priority( char a, char b ){
    int ans = 0;
    switch(a){
        case '*':
        case '/':ans ++;
        case '+':
        case '-':ans ++;   
    }
    switch(b){
        case '*':
        case '/':ans --;
        case '+':
        case '-':ans --;   
    }
    if(ans>0) return 1;
    if(ans<0) return -1;
    return 0;
}


char *middle_to_last( char *toreverse ){
    char *ans = malloc( sizeof(char) * MAX_EXPRESSION_SIZE ), *p_ans = ans;
    SqStack stack, *p_stack = &stack;
    stack.top = -1;

    while( *toreverse != '\0' ){

        // number
        if( '0' <= *toreverse && *toreverse <= '9' ){
            while( '0' <= *toreverse && *toreverse <= '9' ){
                *p_ans++ = *toreverse++;
            }
            *p_ans++ = '_';
        }
        
        if( *toreverse == '\0' ) break;

        // operator
        if( stack.top == -1 || *toreverse == '(' || stack.data[stack.top] == '(' ){
            Push( *toreverse++, p_stack );
        }else if( *toreverse == ')' ){
            while( stack.data[stack.top] != '(' ){
                Pop( p_ans++, p_stack );
            }
            stack.top -= 1;
            toreverse ++;
        }else{
            if( find_priority( *toreverse, stack.data[stack.top] ) > 0 ){
                Push( *toreverse++, p_stack );
            }else{
                while( find_priority( *toreverse, stack.data[stack.top] ) <= 0 ){
                    Pop( p_ans++, p_stack );
                }
                Push( *toreverse++, p_stack );
            }
        }

    }
    while( stack.top > -1 ){
        Pop( p_ans++, p_stack );
    }
    *p_ans = '\0';

    return ans;
}


char *get_stack_num( SqStack *s ){

    char *ans = malloc( sizeof(char) * MAX_NUM_SIZE ), *p_ans = ans;

    s->top --;
    while( s->data[s->top] != '_' && s->top > -1 ){
        Pop( p_ans++, s );
    }
    *p_ans = '\0';

    return reverse(ans);
}


char *last_to_ans( char *last ){
    SqStack stack;
    SqStack *s = &stack;
    stack.top = -1;

    while ( *last != '\0' ){
        if( '0' <= *last && *last <= '9' ){
            while( *last != '_' ){
                Push( *last++, s );
            }
            Push( *last++, s );
        }else{
            char *b = get_stack_num( s );
            char *a = get_stack_num( s );
            // printf("%s\n%s\n",b,a);
            char *c = myoperate( a, b, *last ), *p_c = c;

            while( *p_c != '\0' ){
                Push( *p_c++, s );
            }
            Push( '_', s );
            last ++;
        }

    }

    char *ans = malloc( sizeof(char) * MAX_NUM_SIZE ), *p_ans = ans;
    while( s->top > -1 ){
        Pop( p_ans++, s );
    }
    *p_ans = '\0';
    reverse(ans);
    p_ans --;
    *p_ans = '\0';
    return ans;
}
